package com.walala.logic.service;

import com.walala.logic.common.Constant;
import com.walala.logic.redis.RedisClient;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.walala.logic.cache.ClientCache;
import com.walala.logic.client.ToGatewayClient;
import com.walala.logic.common.Command;
import com.walala.logic.protocol.ProtocolPackage;
import com.walala.logic.utils.IPUtils;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;

import java.util.Map;

/**
 * 发包执行类
 * @author KayLi
 *
 */
public class SendDataService {

	private static Logger logger = LoggerFactory.getLogger(SendDataService.class);
	
	public static void send(long userId,ProtocolPackage pack){

		//获取接受者接入层连接信息
		String connectorInfoKey = Constant.Redis_Connector_key + userId;
		Map<String, String> connectorInfo = RedisClient.intance.getCluster().hgetAll(connectorInfoKey);

		for (String key : connectorInfo.keySet()) {
			String address = connectorInfo.get(key);
			if(StringUtils.isBlank(address)){
				logger.info("send to user fail, connectorInfo error,userId:{},clientOs:{},address:{}",userId,key,address);
				return;
			}

			String[] split = address.split(":");
			String ip = split[0];
			int port = Integer.parseInt(split[1]);
			if(Command.HEART_BEAT != pack.getCommand()) {
				Channel channel = ClientCache.toGatewayChennel.get(address);
				if(channel == null || !channel.isActive()) {
					ClientCache.toGatewayChennel.remove(address);
					channel = ToGatewayClient.getInstance().getChannel(ip,port);
				}
				channel.writeAndFlush(pack).addListener(new ChannelFutureListener() {
					public void operationComplete(ChannelFuture future) throws Exception {
						if (future.isSuccess()) {
							logger.info("[to gateway] send msg success,traceId:[{}],senderId:[{}],receiverId:[{},ack:[{}]",pack.getTraceId(),pack.getSenderId(),pack.getReceiverId()
									,pack.getAck());
						} else {
							logger.error("[to gateway] send msg fail,traceId:[{}],senderId:[{}],receiverId:[{},ack:[{}]",pack.getTraceId(),pack.getSenderId(),pack.getReceiverId()
									,pack.getAck());
						}
					}
				});

			}
		}

	}

}
